/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session04;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 *
 * @author cibervn
 */
public class Encrypt {

    private static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {
        try {
            //Declaration
            String fileOriginal;
            String fileEncrypted;

            //Input
            System.out.println("File to encrypt:");
            fileOriginal = keyboard.nextLine();

            System.out.println("Encrypted file:");
            fileEncrypted = keyboard.nextLine();

            //Getting secrete key
            System.out.print("Enter your password:");
            char[] password = keyboard.nextLine().toCharArray();

            //Init
            byte[] salt = {
                (byte) 0x12, (byte) 0x32, (byte) 0x12, (byte) 0x56,
                (byte) 0x12, (byte) 0x32, (byte) 0x12, (byte) 0x56
            };
            int count = 20;

            PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, count);
            PBEKeySpec keySpec = new PBEKeySpec(password);

            SecretKeyFactory keyFactor = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey sk = keyFactor.generateSecret(keySpec);

            encrypt(fileOriginal, fileEncrypted, sk, parameterSpec);

        } catch (Exception ex) {
        }
    }

    private static void encrypt(String dataFile, String encrytedFile, SecretKey skey, PBEParameterSpec parameterSpec) {
        try {
            //Read plain from file
            BufferedReader br = new BufferedReader(new FileReader(dataFile));
            String original = br.readLine();
            br.close();
            //Get Cipher
            Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
            //Init
            c.init(Cipher.ENCRYPT_MODE, skey, parameterSpec);

            //Encrypt
            byte[] encrypted = c.doFinal(original.getBytes());

            //Save to file
            DataOutputStream dos = new DataOutputStream(new FileOutputStream(encrytedFile));
            dos.writeUTF(Base64.encode(encrypted));
            dos.close();
        } catch (Exception ex) {
        }
    }
}
